package com.common.www.utils;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class TimeUtils {
    private static SimpleDateFormat sdFormat = null;
    public static String YMD_HMS = "yyyy-MM-dd HH:mm:ss";
    public static String YMD_HM = "yyyy-MM-dd HH:mm";
    public static String HM = "HH:mm";
    public static String HMS = "HH:mm:ss";
    public static String YMD = "yyyy-MM-dd";
    public static String YM = "yyyy-MM";

    /**
     * 把服务器的时间转换为本地utc 时间
     *
     * @param time
     * @return
     */
    public static String convert2LocalUTCTime(String time) {
        return convert2LocalUTCTime(time, YMD_HMS);
    }

    public static String convert2LocalUTCTime(String time, String dformat) {
        String localTime = null;
        try {

            if (time == null || time.equals("")) {
                return "";
            }
            SimpleDateFormat format = new SimpleDateFormat(dformat);
            // format.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date gpsUTCDate = null;
            try {
                gpsUTCDate = format.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            format.setTimeZone(TimeZone.getDefault());
            localTime = format.format(gpsUTCDate);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return localTime;
    }

    /**
     * 计算年龄
     */
    public static int getAge(String time) {
        int age = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDay;
        try {
            birthDay = sdf.parse(time);

            Calendar cal = Calendar.getInstance();
            if (cal.before(birthDay)) {
                throw new IllegalArgumentException("出生时间大于当前时间!");
            }

            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH) + 1;
            int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
            cal.setTime(birthDay);
            int yearBirth = cal.get(Calendar.YEAR);
            int monthBirth = cal.get(Calendar.MONTH);
            int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
            age = yearNow - yearBirth;
            if (monthNow <= monthBirth) {
                if (monthNow == monthBirth) {
                    // monthNow==monthBirth
                    if (dayOfMonthNow <= dayOfMonthBirth) {
                        age--;
                    }
                } else {
                    // monthNow>monthBirth
                    age--;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return age;
    }

    /**
     * 计算月份
     */
    public static int getMonth(String time) {
        int ageMonth = 0;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDay;
        try {
            birthDay = sdf.parse(time);

            Calendar cal = Calendar.getInstance();
            if (cal.before(birthDay)) {
                throw new IllegalArgumentException("出生时间大于当前时间!");
            }

            int monthNow = cal.get(Calendar.MONTH) + 1;
            int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
            cal.setTime(birthDay);
            int monthBirth = cal.get(Calendar.MONTH);
            int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

            if (monthBirth < monthNow) {
                ageMonth = monthNow - monthBirth;
                if (dayOfMonthBirth <= dayOfMonthNow) {
                    ageMonth--;
                }

            } else {
                ageMonth = 12 - (monthBirth - monthNow);
                if (dayOfMonthBirth <= dayOfMonthNow) {
                    ageMonth--;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return ageMonth;
    }

    /**
     * <li>功能描述：时间相减得到天数
     */
    public static int reduceDays(String dateStr1, String dateStr2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dateStr1 = sdf.format(sdf2.parse(dateStr1));
            dateStr2 = sdf.format(sdf2.parse(dateStr2));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int year1 = Integer.parseInt(dateStr1.substring(0, 4));
        int month1 = Integer.parseInt(dateStr1.substring(4, 6));
        int day1 = Integer.parseInt(dateStr1.substring(6, 8));
        int year2 = Integer.parseInt(dateStr2.substring(0, 4));
        int month2 = Integer.parseInt(dateStr2.substring(4, 6));
        int day2 = Integer.parseInt(dateStr2.substring(6, 8));
        Calendar c1 = Calendar.getInstance();
        c1.set(Calendar.YEAR, year1);
        c1.set(Calendar.MONTH, month1 - 1);
        c1.set(Calendar.DAY_OF_MONTH, day1);
        Calendar c2 = Calendar.getInstance();
        c2.set(Calendar.YEAR, year2);
        c2.set(Calendar.MONTH, month2 - 1);
        c2.set(Calendar.DAY_OF_MONTH, day2);
        long mills = c1.getTimeInMillis() > c2.getTimeInMillis() ? c1
                .getTimeInMillis() - c2.getTimeInMillis() : c2
                .getTimeInMillis() - c1.getTimeInMillis();
        return (int) (mills / 1000 / 3600 / 24);
    }

    /**
     * 时期短时间相减，
     *
     * @return 返回相减后的时间戳
     */
    public static long differShort(String start, String end) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            start = sdf.format(sdf2.parse(start));
            end = sdf.format(sdf2.parse(end));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int year1 = Integer.parseInt(start.substring(0, 4));
        int month1 = Integer.parseInt(start.substring(4, 6));
        int day1 = Integer.parseInt(start.substring(6, 8));
        int hour1 = Integer.parseInt(start.substring(8, 10));
        int minute1 = Integer.parseInt(start.substring(10, 12));

        int year2 = Integer.parseInt(end.substring(0, 4));
        int month2 = Integer.parseInt(end.substring(4, 6));
        int day2 = Integer.parseInt(end.substring(6, 8));
        int hour2 = Integer.parseInt(end.substring(8, 10));
        int minute2 = Integer.parseInt(end.substring(10, 12));

        Calendar c1 = Calendar.getInstance();
        c1.set(Calendar.YEAR, year1);
        c1.set(Calendar.MONTH, month1 - 1);
        c1.set(Calendar.DAY_OF_MONTH, day1);
        c1.set(Calendar.HOUR_OF_DAY, hour1);
        c1.set(Calendar.MINUTE, minute1);

        Calendar c2 = Calendar.getInstance();
        c2.set(Calendar.YEAR, year2);
        c2.set(Calendar.MONTH, month2 - 1);
        c2.set(Calendar.DAY_OF_MONTH, day2);
        c2.set(Calendar.HOUR_OF_DAY, hour2);
        c2.set(Calendar.MINUTE, minute2);

        long mills = c2.getTimeInMillis() - c1.getTimeInMillis();
        return mills;
    }

    /**
     * 把时间格式转换为时间戳
     */
    public static long getTimestamp(String time) {
        SimpleDateFormat format = new SimpleDateFormat(YMD_HMS);
        try {
            Date data = format.parse(time);
            return data.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 把时间格式转换为时间戳
     */
    public static long getTimestamp(String time, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            Date data = format.parse(time);
            return data.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 时间戳转换为时间格式
     */
    public static String getTimeStringByTimetamp(String time, String pattern) {
        if (time == null || "".equals(time) || "0".equals(time))
            return "";
        if (pattern == null || "".equals(pattern)) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        long tmp = 0;
        try {
            tmp = Long.parseLong(time);
        } catch (Exception e) {
        }
        if (tmp == 0)
            return "";
        String date = format.format(tmp);
        return date;
    }

    /**
     * 时间戳转换为时间格式
     */
    public static String getTimeStringByTimetamp(String time) {
        if (time == null || "".equals(time) || "0".equals(time))
            return "";
        if (YMD_HMS == null || "".equals(YMD_HMS)) {
            YMD_HMS = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat format = new SimpleDateFormat(YMD_HMS);
        long tmp = 0;
        try {
            tmp = Long.parseLong(time);
        } catch (Exception e) {
        }
        if (tmp == 0)
            return "";
        String date = format.format(tmp);
        return date;
    }

    /**
     * 时间戳转换为时间格式 (long)
     */
    public static String getTimeStringByTimetamp(long time, String pattern) {
        if (pattern == null) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String date = format.format(new Date(time));
        return date;
    }

    /**
     * 时间戳转换为时间格式 (long)
     */
    public static String getTimeStringByTimetamp(long time) {
        if (YMD_HMS == null) {
            YMD_HMS = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat format = new SimpleDateFormat(YMD_HMS);
        String date = format.format(new Date(time));
        return date;
    }

    public static String timeFormat(long timeMillis, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.CHINA);
        return format.format(new Date(timeMillis));
    }

    public static String formatPhotoDate(long time) {
        return timeFormat(time, "yyyy-MM-dd");
    }

    /**
     * 得到照片拍摄时间
     */
    public static String formatPhotoDate(String path) {
        File file = new File(path);
        if (file.exists()) {
            long time = file.lastModified();
            return formatPhotoDate(time);
        }
        return "1970-01-01";
    }

    /**
     * 格式化时间，格式为 00:00,单位为毫秒
     */
    public static String formatTime(String time) {
        return formatTime(TxtUtil.getLong(time));
    }

    /**
     * 格式化时间，格式为 00:00,单位为毫秒
     *
     * @param time 毫秒
     */
    public static String formatTime(long time) {
        if (time < 0)
            return "00:00";

        String res = "";

        int tmp = (int) (time / 1000);
        int hour = tmp / 3600;
        int minute = tmp / 60 % 60;
        int secound = tmp % 60;
        res += (hour > 0 ? (((hour / 10 >= 1) ? hour + "" : ("0" + hour)) + ":") : "")
                + ((minute / 10 >= 1) ? minute + "" : ("0" + minute)) + ":"
                + ((secound / 10 >= 1) ? secound + "" : ("0" + secound)) + "";

        return res;
    }

    /**
     * 单位为毫秒
     */
    public static String getWeek(String time) {
        return getWeek(TxtUtil.getLong(time));
    }

    /**
     * 单位为毫秒
     */
    public static String getWeek(long time) {
        String pattern = "EE";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String date = format.format(new Date(time));
        return date;
    }

    public static String getLocalDate(String pattern) {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(pattern));
    }

    public static String getLocalDate() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(YMD_HMS));
    }

    public static Long getLocalDatestamp() {
        return new Date().getTime();
    }


    /**
     * 获取两个时间之间的时间区间
     * @param start 开始日期
     * @param end  结束日期
     * @return
     */
    public static List<String> getDateDifferEveryDay(String start,String end){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormatString = new SimpleDateFormat( "yyyy-MM-dd");
        try {
            Date startDate =simpleDateFormat.parse(start);
            Date endDate =simpleDateFormat.parse(end);
            List<String> result = new ArrayList<>();
            while (startDate.getTime()<endDate.getTime()){
                result.add(simpleDateFormatString.format(startDate));
                startDate.setTime(startDate.getTime()+24*60*60*1000);
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

}
